package com.baidu.foodrecipe.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.baidu.foodrecipe.data.model.ExtendedIngredient
import com.baidu.foodrecipe.data.model.Result
import com.baidu.foodrecipe.databinding.FragmentIngredientsBinding
import com.baidu.foodrecipe.databinding.IngredientItemBinding
import com.baidu.foodrecipe.utils.BASE_URL
import com.baidu.foodrecipe.utils.IMAGE_BASE_URL
import com.bumptech.glide.Glide

class IngredientsAdapter : RecyclerView.Adapter<IngredientsAdapter.MyViewHolder>() {
    private var ingredientsList = emptyList<ExtendedIngredient>()
    private var result: Result? = null

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MyViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return MyViewHolder(IngredientItemBinding.inflate(inflater))
    }

    override fun onBindViewHolder(
        holder: MyViewHolder,
        position: Int
    ) {
        holder.bind(ingredientsList[position], result!!)
    }

    override fun getItemCount(): Int {
        return ingredientsList.size
    }

    class MyViewHolder(val binding: IngredientItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(ingredient: ExtendedIngredient, result: Result) {
            Glide.with(binding.root.context)
                .load("${IMAGE_BASE_URL}/${ingredient.image}")
                .into(binding.image)

            binding.name.text = ingredient.name
            binding.amount.text = ingredient.amount.toString()
        }
    }

    fun setNewData(newData: Result) {
        ingredientsList = newData.extendedIngredients
        result = newData
        notifyDataSetChanged()

    }
}